from __future__ import unicode_literals

import requests
import pandas as pd
import time
import sys


def search_location(address):
    params = {'address': address,
              'city': '广州',
              'key': '67563005142dfa10fe2d1020b12b3655'}
    base_url = 'http://restapi.amap.com/v3/geocode/geo'
    response = requests.get(url=base_url, params=params)
    json_data = response.json()
    if json_data['status'] == '1' and len(json_data['geocodes']) > 0:
        return json_data['geocodes'][0]['location'] if json_data['geocodes'][0]['location'] else 'errorlocation', json_data
    return 'errorlocation', json_data


def search_address_detail(location):
    params = {'location': location,
              'key': '67563005142dfa10fe2d1020b12b3655'}
    base_url = 'http://restapi.amap.com/v3/geocode/regeo'
    response = requests.get(url=base_url, params=params)
    json_data = response.json()
    if json_data['status'] == '1':
        if json_data['regeocode']['addressComponent']['township']:
            return json_data['regeocode']['addressComponent']['township'], json_data
    return 'errorSearchAddress', json_data


if __name__ == '__main__':
    location_str, search_json = search_location("广东省广州市越秀区东兴北路66号601房")
    print(location_str)
    print(search_json)
    township_str, search_address_json = search_address_detail(location=location_str)
    print(search_address_json)
    print(township_str)